import {lazyReportCache} from "../utils/report.js";
import {xhrPrototype, xhrSend, xhrOpen} from "../utils/common.js"

/**
 * 网络请求的监控（基于XMLHttpRequest封装的请求插件）
 * */
function overwrite() {
    // 重写open。用于初始化一个新的 HTTP 请求，设置请求的基本参数
    xhrPrototype.open = function (...args) {
        this.url = args[1]
        this.method = args[0]
        xhrOpen.apply(this, args)
    }
    // 发送一个请求
    xhrPrototype.send = function (...args) {
        this.startTime = Date.now()

        const onLoadend = () => {
            this.endTime = Date.now()
            this.duration = this.endTime - this.startTime

            const { status, duration, startTime, endTime, url, method } = this
            const data = {
                type: 'performance',
                subType: 'xhr',
                url,
                status,
                duration,
                startTime,
                endTime,
                method: (method || 'GET').toUpperCase(),
                success: status >= 200 && status < 300,
            }
            lazyReportCache(data)
            
            this.removeEventListener('loadend', onLoadend, true)
        }
        // this指向xhrPrototype
        this.addEventListener('loadend', onLoadend, true)
        xhrSend.apply(this, args)
    }
}

export default function observeXhrRequest() {
    overwrite()
}
